package wang.naifei.core.utils.image;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;

public class ImageUtil {

    private static final Logger log = LoggerFactory.getLogger(ImageUtil.class);

    /**
     * 将本地图片进行Base64位编码
     *
     * @param inputStream 图片的流
     * @param formatName  图片格式
     * @return
     */
    public static String encodeImageToBase64(InputStream inputStream, String formatName) {
        String base64Image = null;
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(inputStream);
        } catch (IOException e) {
            log.error("ImageIO read error", e);
        }
        if (bufferedImage != null) {
            base64Image = encodeImageToBase64(bufferedImage, formatName);
        }
        return base64Image;
    }

    /**
     * 将图片进行Base64位编码
     *
     * @param bufferedImage 图片buffer
     * @param formatName    图片格式
     * @return
     */
    public static String encodeImageToBase64(BufferedImage bufferedImage, String formatName) {
        String base64Image = null;
        if (bufferedImage != null) {
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();) {
                ImageIO.write(bufferedImage, formatName, outputStream);
                // 对字节数组Base64编码
                base64Image = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            } catch (IOException e) {
                log.error( "ImageIO read error", e);
            }
        }
        return base64Image;// 返回Base64编码过的字节数组字符串
    }

    /**
     * 将Base64位编码的图片进行解码，并保存到指定目录
     *
     * @param base64String base64编码的图片信息
     * @return
     */
    public static void decodeBase64ToImage(String base64String, String path, String imgName) {
        try (FileOutputStream write = new FileOutputStream(new File(path, imgName));) {
            byte[] decoderBytes = Base64.getDecoder().decode(base64String);
            write.write(decoderBytes);
        } catch (IOException e) {
            log.error( "ImageIO read error", e);
        }
    }

}
